package thread;

import java.sql.SQLOutput;

/**
 * @author DBX
 * @effect 死锁指的是两个（或多个）线程各自持有一个锁的同时等待对方释放其持有的锁的一种现象，
 *          此时会出现一种僵持状态，导致程序永远无法继续后续的执行
 * @date 2021/09/01/19:05
 */
public class DeadLockDemo {
    private static Object spoon =  new Object();//勺
    private static Object chopsticks = new Object();//筷子

    public static void main(String[] args) {
        Thread np = new Thread("北方人---"){
            String name = getName();
            @Override
            public void run() {
                System.out.println(name+":开始吃饭");
                System.out.println(name+":去拿筷子...");
                synchronized (chopsticks){
                    System.out.println(name+":拿起筷子吃饭。。。");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(name+":吃完饭，去拿勺---------死锁");
                    synchronized (spoon){
                        System.out.println(name+":拿起勺喝了汤");
                        try {
                            Thread.sleep(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(name+":喝完汤放下筷子");
                }
            }
        };
        Thread sp = new Thread("南方人---"){
            String name = getName();
            @Override
            public void run() {
                System.out.println(name+":开始吃饭");
                System.out.println(name+":去拿勺子...");
                synchronized (spoon){
                    System.out.println(name+":拿起勺子喝汤。。。");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(name+":吃完汤，去拿筷子------------死锁");
                    synchronized (chopsticks){
                        System.out.println(name+":拿起筷子吃了饭");
                        try {
                            Thread.sleep(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(name+":放下筷子喝完了汤");
                }
            }
        };
        np.start();
        sp.start();
    }
}
